﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using Autodesk.Revit.UI;
using Autodesk.Revit.DB;
using System.Windows.Forms;
using MongoDB.Driver;
using MongoDB.Bson;

namespace component
{

    /// <summary>
    /// Page1.xaml 的交互逻辑
    /// </summary>
    public partial class Page1 : System.Windows.Controls.UserControl
    {


        private ScrollViewer scrollViewer = new ScrollViewer();
        //public MainWindow mainWindow;
        public static string serverIp = "127.0.0.1";//设置服务端IP
        public static int serverPort = 8888;//服务端端口
        public static Socket socketClient;//定义socket
        public Page1()
        {
            
            //this.commandData = commandData;
            InitializeComponent();
        }
        //下载
        private void download(object sender, RoutedEventArgs e)
        {
            //mainWindow.downLoad(sender, e, "混凝土梁 - 矩形砼梁 - 有标记.rfa");

            socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个socket的对象
            IPAddress ip = IPAddress.Parse(serverIp);//获取服务器IP地址
            IPEndPoint point = new IPEndPoint(ip, serverPort);//获取端口
            try
            {
                socketClient.Connect(point);//链接服务器IP与端口
                Console.WriteLine("连接服务器中.....");

            }
            catch (Exception)
            {
                Console.WriteLine("与服务器链接失败！");
                return;
            }
            Console.WriteLine("与服务器链接成功！");
            String filename = "混凝土梁-矩形砼梁-有标记.rfa";
            byte[] filename_Byte = System.Text.Encoding.UTF8.GetBytes(filename);//文件名的数组
            byte[] filenameLength = new byte[1];//文件名长度的数组
            byte[] MD5 = new byte[1];//MD5的数组
            filenameLength[0] = (byte)filename_Byte.Length;
            socketClient.Send(filenameLength);//发送文件名长度
            socketClient.Send(filename_Byte);//发送文件名
            Console.Write("发送请求完毕");
            byte[] fileLength = new byte[socketClient.ReceiveBufferSize];//接受文件长度的数组
            socketClient.Receive(fileLength);//接受文件长度
            socketClient.Receive(MD5);
            long filelong = BytesToLong(fileLength);
            string MD51 = System.Text.Encoding.Default.GetString(MD5);
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            Console.WriteLine("执行完毕");
            dialog.ShowDialog();
            string file_path = dialog.SelectedPath;
            //得到选择文件的路径
            //string spath = @"E:\存放";//制定存储路径
            string savePath = System.IO.Path.Combine(file_path, filename);//获取存储路径及文件名
            FileStream fileStream1 = new FileStream(savePath, FileMode.Create, FileAccess.Write);
            int rec = 0;//每次转换的长度
            long recFileLength = 0;//接受的文件长度
            byte[] buffer = new byte[1024];//接受文件的数组
            while (recFileLength < filelong)
            {
                rec = socketClient.Receive(buffer);
                fileStream1.Write(buffer, 0, rec);
                fileStream1.Flush();
                recFileLength++;
            }
            if (MD51 == Commons.GetMD5HashFromFile(savePath)) Console.WriteLine($"接受成功");
            else Console.WriteLine($"接受失败");
            fileStream1.Close();
        }
        //将字符数组转换成Long型的方法
        static long BytesToLong(byte[] bytes)
        {
            return BitConverter.ToInt64(bytes, 0);
        }

        private void homeBeamParameter(object sender, RoutedEventArgs e)
        {
            if (ifShow != 1)
            {
                if (ifShow == 2)
                    this.scrollViewer = new ScrollViewer();
                ifShow = 1;
                page1.Children.Add(scrollViewer);
                System.Windows.Controls.TextBox textBox = new System.Windows.Controls.TextBox();
                scrollViewer.Content = textBox;
                //1.连接字符串（mongodb数据库默认端口为：27017）
                string connStr = "mongodb://127.0.0.1:27017";

                //2.创建连接MongoClient实例实际上代表了一个到数据库的连接池，即使有多个线程，也只需要一个MongoClient类的实例
                var client = new MongoClient(connStr);

                //3.使用client的GetDatabase方法获取数据库，即使该数据库不存在，也会自动创建；
                IMongoDatabase db = client.GetDatabase("test");
                //4.获取数据集 collection；BsonDocument是在数据没有预先定义好的情况下使用的。
                IMongoCollection<BsonDocument> collection = db.GetCollection<BsonDocument>("family");

                //6.查询整个数据集
                var res = collection.Find(new BsonDocument()).ToList();


                foreach (var item in res)
                {
                    a = 0;
                    string information_item = item.ToString();

                    foreach (var c in information_item)
                    {

                        if (c == '{' || c == '\"' || c == '}')
                        {
                            continue;
                        }

                        if (c == ',')
                        {
                            a++;
                            if (a == 1)
                                continue;

                            else
                            {
                                textBox.AppendText("\n");
                                continue;
                            }

                        }
                        if (a == 0)
                        {
                            continue;
                        }
                        else
                            textBox.AppendText(c + "");

                    }

                }
            }
            else if(ifShow == 1)
            {
                page1.Children.Remove(scrollViewer);
                this.scrollViewer = null;
                ifShow = 2;
            }
        }      
        
        //构件按钮效果
        private void button_visible(object sender, RoutedEventArgs e)
        {
            set.Visibility = System.Windows.Visibility.Visible;
            load.Visibility = System.Windows.Visibility.Visible;
        }
        private void button_hiddin(object sender, RoutedEventArgs e)
        {
            set.Visibility = System.Windows.Visibility.Collapsed;
            load.Visibility = System.Windows.Visibility.Collapsed;
        }
        private int a = 0;
        private int ifShow = 0;
    }
}
